package Chatroom;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

// 客户端接收消息的线程类
class Read implements Runnable {
    Socket socket = null;
    public Read(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            if (socket != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {
                    String line = in.readLine();
                    if (line != null && !"".equals(line)) {
                        System.out.println(line);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// 客户端类
public class ChatClient implements Runnable {
    static Socket socket = null;
    static Scanner input = new Scanner(System.in);
    static String name = null;

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String message = input.nextLine();
                out.println(name +" 说: " + message);
                out.flush();
            }
        } catch (Exception e) {
            System.out.println("[" + name + "] 写消息失败！");
            e.printStackTrace();
        }
    }

    // 注册新客户端
    public void register(String name, String from) {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            String profileInfo = "[SYS]" + name + ";" + from;
            out.println(profileInfo);
            out.flush();
        } catch (Exception e) {
            System.out.println("[" + name + "] 注册失败！");
        }
    }

    public static void main(String[] args) {
        int clientNumber = (int)(Math.random() * 100);
        System.out.println("************ 客户端" + clientNumber + " *************");
        System.out.println("请输入您的昵称：");
        String name = input.nextLine();
        System.out.println("请输入您来自哪里：");
        String from = input.nextLine();
        ChatClient.name = "[" + clientNumber + "][" + from + "-" + name + "]";

        try {
            socket = new Socket("127.0.0.1", 9999);
            if (socket != null) {
                System.out.println("服务器已连接！");
                //
                ChatClient t = new ChatClient();
                t.register(name, from);
                Read r = new Read(socket);

                // 开启写线程和读线程
                Thread write = new Thread(t);
                Thread read = new Thread(r);
                write.start();
                read.start();
            }
        } catch (Exception e) {
            System.out.println("连接服务器失败！原因【" + e.getMessage()+ "】");
        }
    }
}
